package com.atguigu.gmall.cart.controller;

import com.atguigu.gmall.cart.service.CartInfoService;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author ：MJS
 * @date ：Created in 2021/5/21  20:00
 * @description：TODO 购物车管理
 * 加入购物车
 * 查询购物车
 */
@RestController
@RequestMapping("/api/cart")
public class CartInfoApiController {
    @Autowired
    private CartInfoService cartInfoService;

    //加入购物车
    @GetMapping("/addToCart/{skuId}/{skuNum}")
    public void addToCart(@PathVariable Long skuId, @PathVariable Integer skuNum, HttpServletRequest request) {
        //真实用户id
        String userId = AuthContextHolder.getUserId(request);
        if (StringUtils.isEmpty(userId)) {
            //这样写的好处  是  若有真实id传真实  若是临时id传临时
            userId = AuthContextHolder.getUserTempId(request);
        }
        cartInfoService.addToCart(skuId, skuNum, userId);
    }

    //去购物车添加成功界面
    @GetMapping("/toCart/{skuId}")
    public CartInfo toCart(@PathVariable Long skuId) {
        return cartInfoService.toCart(skuId);
    }

    //查询购物车集合
    @GetMapping("/cartList")
    public Result cartList(HttpServletRequest request) {
        //用户id   此用户的购物车的所有
        String userId = AuthContextHolder.getUserId(request);
        //临时用户ID
        String userTempId = AuthContextHolder.getUserTempId(request);
        //1.如果未登录  只显示未登录时的购物车集合
        //2.如果已登录   显示未登录时加入的购物车集合  并集 上已登录时加入购物车的集合

        List<CartInfo> cartInfoList = cartInfoService.cartList(userId, userTempId);
        return Result.ok(cartInfoList);
    }

    //选中或取消购物车
    @GetMapping("/checkCart/{skuId}/{isChecked}")
    public Result checkCart(@PathVariable Long skuId, @PathVariable Integer isChecked) {
        cartInfoService.checkCart(skuId, isChecked);
        return Result.ok();
    }

    //商品清单  购物车中选中了商品集合
    @GetMapping("/checkedCartInfoList")
    public List<CartInfo> checkedCartInfoList(HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        return cartInfoService.checkedCartInfoList(userId);
    }
}
